<template>
    <div class="read-main" @scroll="scrollAction()">
        <div id="topId"></div>
        <div class="cover full-screen-window" v-if="changeModelTool"></div>
        <div class="read-wrapper" :class="[{'night-read-wrapper':changeModelTool},skinColor]">
            <p class="title">{{readData.title || ' '}}</p>
            <div class="btn-wrapper">
                <nuxt-link :to="{path:'/read',query:lastQuery}"><button class="last-chapter" @click="getLastChapter">上一章</button></nuxt-link>
                <nuxt-link to="/"><button class="back-home">首页</button></nuxt-link>
                <nuxt-link :to="{path:'/read/catalog',query:{novelId:readData.novelId,siteId:readData.siteId,cId:readData.cid,name:storeInfo.name}}"><button class="back-catalog">目录</button></nuxt-link>
                <nuxt-link :to="{path:'/read',query:nextQuery}"><button class="next-chapter" @click="getNextChapter">下一章</button></nuxt-link>
            </div>
            <div class="tool-wrapper flex align-center">
                <span class="source">换源：<nuxt-link :to="{path:'/read/source',query:currentQuery}"><em @click="$router.push('')">{{readData.siteName}}</em></nuxt-link></span>
                <div class="right">
                    <span @click="changeSkinTool=!changeSkinTool">换肤</span>
                    <i class="change-skin" :class="{'night-skin':!changeModelTool,'day-skin':changeModelTool}" @click="changeModelToolAction"></i>
                    <span @click="setFontSize(0)">A-</span>
                    <span @click="setFontSize(1)">A+</span>
                </div>
                <span class="triangle-icon" v-if="changeSkinTool"></span>
                <div class="skin-wrapper justify-align-center" v-if="changeSkinTool">
                    <span class="skin-1" @click="changeSkinColorAction('skin-1')"></span>
                    <span class="skin-2" @click="changeSkinColorAction('skin-2')"></span>
                    <span class="skin-3" @click="changeSkinColorAction('skin-3')"></span>
                    <span class="skin-4" @click="changeSkinColorAction('skin-4')"></span>
                    <span class="skin-5" @click="changeSkinColorAction('skin-5')"></span>
                    <span class="skin-6" @click="changeSkinColorAction('skin-6')"></span>
                </div>
            </div>
            <!-- 小说正文 -->
            <div class="content" :style="{'font-size': `${fontSize}px`}" v-html="contnetFilter(readData.content)">
               
            </div>

            <div class="btn-wrapper">
                <nuxt-link :to="{path:'/read',query:lastQuery}"><button class="last-chapter" @click="getLastChapter">上一章</button></nuxt-link>
                <nuxt-link to="/"><button class="back-home">首页</button></nuxt-link>
                <nuxt-link :to="{path:'/read/catalog',query:{novelId:readData.novelId,siteId:readData.siteId,chapterId:chapterId}}"><button class="back-catalog">目录</button></nuxt-link>
                <nuxt-link :to="{path:'/read',query:nextQuery}"><button class="next-chapter" @click="getNextChapter">下一章</button></nuxt-link>
            </div>
        </div>
        <div class="hot-wrapper">
            <div class="header">
            <span class="line"></span><span class="plate-title">热门推荐</span>
            </div>
            <div class="like-content">
                <div class="list">
                    <ul>
                        <router-link tag="li" :to="'/novelDetail/'+item.novelId" v-for="(item,index) in hotArray" :key="index">
                            <div class="left"><img :src="item.cover" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null" class="novel-icon"></div>
                            <div class="right">
                                <p class="ellipsis title">{{item.name}}</p>
                                <p class="ellipsis">{{item.author}}</p>
                                <p class="ellipsis">{{item.intro}}</p>
                                <p class="ellipsis">{{item.marknum}}人在追 | {{item.retention}}读者留存</p>
                            </div>
                        </router-link>
                    </ul>
                </div>
            </div>
        </div>
        <div class="cover full-screen-window" v-if="presentMoneyTool"></div>
        <div class="present-money-wrapper" v-if="presentMoneyTool">
            <div class="header"><em class="cancel" @click="cancelPresentMoneyTool"></em></div>
            <div class="content">
                <div class="item" :class="`item${index}`" v-for="(item,index) in currenCountArray" :key="index" @click="clickPresentMoney(item,index)">
                    <i :class="`class${item.money}-0`" v-show="item.state==0"></i>
                    <i :class="`class${item.money}-1`" v-show="item.state==1"></i>
                    <i :class="`class${item.money}-2`" v-show="item.state==2"></i>
                    <p class="text" style="color:#b9b29b" v-show="item.state==0">已领取</p>
                    <p class="text" style="color:#e2443a" v-show="item.state==1">可领取</p>
                    <p class="text" style="color:#4d4d4d" v-show="item.state==2">累积阅读{{item.time}}分钟</p>
                </div>
            </div>
        </div>
        <div class="loginreg-wrapper" v-if="readLoginBackTool">
            <LoginReg  @readLoginBack="readLoginBackTool=false"></LoginReg>
        </div>
        <div class="footer showGuanggao">
            本站系基于互联网搜索引擎技术为您提供信息
        </div>
        <div class="guanggao-wrapp">
            <img :src="storeInfo.coverimg" :alt="storeInfo.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null">
            <span>
                <p class="download-text">现在下载，随时免费读</p>
                <p class="download-num">140万人已下载</p>
            </span>
            <button @click="downloadAction">下载APP</button>
        </div>
    </div>
</template>
<script>
  import {Toast,Indicator,MessageBox} from 'mint-ui'
  import LoginReg from '~/pages/loginReg/index'
  import api from '~/plugins/api.js'
  import axios from 'axios'
  import qs from 'qs'
  import storage from 'localforage'
  
  const lastTime = 10800
  const intervalTime = 60
  const Multiple = 100
  export default {
    head() {
        return {
            title: `${this.readData.title || ''}- ${this.storeInfo.name} - 快眼看书`,
            meta: [{
                name: 'description',
                content: `快眼看书提供《${this.storeInfo.name}》最新章节的搜索，更新超级快，无病毒无木马，页面干净清爽，希望大家收藏!`
            },{
                name: 'keyWords',
                content: `${this.storeInfo.name} 快眼看书,${this.readData.title},快眼看书`
            }]
        }
    },
    data () {
      return {
          changeSkinTool: false,
          changeModelTool: false,
          skinColor: 'skin-5',
          fontSize: 16,
          novelName: '小说阅读',
          readData: {},
          chapterId: 0,
          lastQuery: {},
          currentQuery: {},
          nextQuery: {},
          hotArray: [],
          storeInfo: {},
          intervalid: null,
          isStopTime: false,
          presentMoneyTool: false,
          countArray: [{ 
              state: 2,  // 2未领取 1可领取 0已领取
              money: 2,
              time: 10,
              duration: 600,
              generate_time: 0
          },{
              state: 2,
              money: 5,
              time: 30,
              duration: 1800,
              generate_time: 0
          },{
              state: 2,
              money: 10,
              time: 60,
              duration: 3600,
              generate_time: 0
          },{
              state: 2,
              money: 15,
              time: 90,
              duration: 5400,
              generate_time: 0
          },{
              state: 2,
              money: 20,
              time: 120,
              duration: 7200,
              generate_time: 0
          },{
              state: 2,
              money: 25,
              time: 150,
              duration: 9000,
              generate_time: 0
          },{
              state: 2,
              money: 30,
              time: 180,
              duration: 10800,
              generate_time: 0
          }],
          currenCountArray: [],
          readTime: 0,
          timesRun: 0,
          submitDataArray: [],
          readLoginBackTool: false
      }
    },
    created() {
        let {query} = this.$route
        this.currentQuery = query
        if(!process.server){
            this.initData()
        } 
    },
    mounted() {
        this.getHotData()
        this.getStoreInfo()
        this.intervalidRun()
        if(this.readData.cid){
            this.getQuery()
        }
    },
    methods: {
        /**
         * 获取上下章参数
         */
        async getQuery() {
            let currentChapterId = parseInt(this.currentQuery.chapterId)
            let currentcId = parseInt(this.readData.cid)
            if(currentChapterId>1){
                this.lastQuery = {
                    novelId: this.currentQuery.novelId,
                    siteId: this.currentQuery.siteId,
                    chapterId: currentChapterId-1,
                    cId: currentcId-1
                }
            }else{
                this.lastQuery = this.currentQuery
            }
            
            if(currentChapterId < this.storeInfo.lastChapterId){
                this.nextQuery = {
                    novelId: this.currentQuery.novelId,
                    siteId: this.currentQuery.siteId,
                    chapterId: currentChapterId+1,
                    cId: currentcId+1
                }
            }else{
                this.nextQuery = this.currentQuery
            }
            
        },
        getLastChapter() {
                if(this.currentQuery.chapterId == 1){
                    Toast('当前已经是第一章')
                    return
                }
                this.currentQuery = this.lastQuery
                this.initData()
        },
        getNextChapter () {
            if(this.currentQuery.chapterId == this.storeInfo.lastChapterId){
                 MessageBox.alert('您已阅读完毕，去书城看看其他书籍吧').then(action => {
                    this.$router.push('/')
                }).catch(resp => {});
                return
            }
                this.currentQuery = this.nextQuery 
                this.initData()
        },
        /**
         * 设置字体大小
         */
        setFontSize(index) {
            if(index&&this.fontSize<30){
                this.fontSize++
            }
            if(!index&&this.fontSize>12){
                this.fontSize--
            }
            storage.setItem('fontSizeKey',this.fontSize)
        },
        async initData() {
           
            this.chapterId = this.currentQuery.chapterId
            Indicator.open({ spinnerType: 'triple-bounce'});
            let res = await axios.get(api.read,{params:this.currentQuery})
            Indicator.close();
            if(res){
                let data = res.data.data
                this.readData = data
                this.getQuery()
                this.saveReadHistory()
                this.$nextTick(() => { 
                    document.getElementById('topId').scrollIntoView() 
                })
                
            }
        },
        async getHotData() {
            this.changeModelTool = await storage.getItem('changeModelToolKey') || false
            this.skinColor = await storage.getItem('skinColorKey') || 'skin-5'
            this.fontSize = await storage.getItem('fontSizeKey') || 16
            let data = await storage.getItem('choice')
            if(data){
               this.hotArray = data.recentUpdate
            }
        },
        /**
         * 保存历史数据
         */
        async saveReadHistory() {
            let novelId = JSON.stringify(parseInt(this.$route.query.novelId))
            let arr = await storage.getItem('saveReadHistoryKey') || []
            Array.prototype.remove = function(val) {
                var index = this.indexOf(val);
                if (index > -1) {
                    this.splice(index, 1);
                }
            };
            arr.remove(novelId)
            arr.unshift(novelId)
            storage.setItem('saveReadHistoryKey',arr)
            // -------------更新时间---------------------

            let bookshelfIdArr = await storage.getItem('bookshelfIdKey') || []
            if(bookshelfIdArr.indexOf(parseInt(this.$route.query.novelId)) > -1){//则包含该元素
                let timestamp = Date.parse(new Date())/1000
                let timeObj = {
                    novelId: novelId,
                    currentQuery: this.currentQuery,
                    lastChapter: this.readData.title,
                    timestamp: timestamp
                }

                let obj = await storage.getItem('timestampKey') || {}
                obj[novelId] = timeObj
                storage.setItem('timestampKey',obj) 

            }
           
        },
        changeModelToolAction() {
            this.changeModelTool=!this.changeModelTool
            storage.setItem('changeModelToolKey',this.changeModelTool)
        },
        changeSkinColorAction(colorStr){
            this.skinColor = colorStr
            storage.setItem('skinColorKey',colorStr)
        },
        async getStoreInfo() {
            let novelId = this.currentQuery.novelId
            let result = await axios.get(api.unLogin,{params:{novelId:novelId}})
            if(result){
                this.storeInfo = result.data.data[0]
            }
        },
        async syncShelfAction(arr) {
            let bookshelfIdArr = await storage.setItem('bookshelfIdKey',arr)
            let userInfo = await storage.getItem('userinfo')
            if(userInfo){
                let paramsData = {
                    novelId: this.currentQuery.novelId,
                    chapterId: '',
                    uid: userInfo.uid,
                    token: userInfo.token
                }
                let result = await axios.post(api.addBookcase,qs.stringify(paramsData))
            }
        },
        /**
         * 监听滚动条
         */
        scrollAction() {
            if(this.isStopTime){
                this.isStopTime = false
                this.intervalidRun()
            }
            if(this.timesRun >5){
                this.timesRun = 0
            }
        },
        /**
         * 启动定时器
         */
        async intervalidRun() {
            let _this = this
            this.timesRun = 0
            this.intervalid = setInterval(function(){
                _this.getReadTime()
            },1000)
        },
        /**
         * 阅读时间
         */
        async getReadTime() {
            let _this = this
            let currenTimeStamp = Math.round(new Date() / 1000) //当前时间戳
            let tomorrowTimeStamp =parseInt(await storage.getItem('tomorrowTimeKey')) || 0  // 第二天0点0分0秒时间戳
            if(currenTimeStamp > tomorrowTimeStamp){ // 到第二天就初始化
                this.isNextDay()
            }else{
                this.readTime = await storage.getItem('readTimeKey') || 0
                this.readTime = parseInt(this.readTime)
                this.currenCountArray = await storage.getItem('currenCountArrayKey') || this.countArray
                if(this.readTime < lastTime){ // 当天领取次数还未用完
                    this.timesRun++
                    this.readTime++
                    this.presentMoneyType(this.readTime)
                    storage.setItem('readTimeKey',this.readTime)
                    //console.log(this.timesRun,'====',this.readTime)
                    if(this.timesRun == intervalTime || this.readTime==lastTime){  //静止不动或次数用完不再计时
                        clearInterval(this.intervalid)
                        this.isStopTime = true
                    }
                   
                }else{ // 次数用完不再计时
                    clearInterval(this.intervalid)
                    this.isStopTime = true
                }

            }

        },
        /**
         *  初始化一天新的的数据
         */
        async isNextDay() {
            clearInterval(this.intervalid)
            let todyTimeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000 // 当天0点0分0秒时间戳
            let tomorrowTimeStamp = todyTimeStamp+86400 // 第二天0点0分0秒时间戳
            this.submitDataArray = []
            this.readTime = 0
            this.currenCountArray = this.countArray
            await storage.setItem('currenCountArrayKey',this.currenCountArray)
            await storage.setItem('tomorrowTimeKey',tomorrowTimeStamp)
            await storage.setItem('readTimeKey',0)
            await storage.removeItem('choosePresentMoneyKey')
            this.intervalidRun()
        },
        /**
         * 一天赠金数量类型
         */
        async presentMoneyType (time){
            let _this = this
            let readTime = parseInt(time)
            switch(readTime) {
                case 6*Multiple:
                    _this.presentMoney(0)
                    break;
                case 18*Multiple:
                    _this.presentMoney(1)
                    break;
                case 36*Multiple:
                    _this.presentMoney(2)
                    break;
                case 54*Multiple:
                    _this.presentMoney(3)
                    break;
                case 72*Multiple:
                    _this.presentMoney(4)
                    break;
                case 90*Multiple:
                     _this.presentMoney(5)
                    break;
                case 108*Multiple:
                     _this.presentMoney(6)
                    break;
                default:
                    
            }
            
        },
        /**
         * 修改一天中赠金信息
         */
        async presentMoney(index) {
            var setupObj = this.currenCountArray[index]
            setupObj['state'] = 1  // 状态改为可领取
            setupObj['generate_time'] = Math.round(new Date() / 1000) // 满足领取条件时的时间戳
            this.$set(this.currenCountArray,index,setupObj)
            storage.setItem('currenCountArrayKey',this.currenCountArray)
            this.presentMoneyTool = true
        },
        /**
         * 取消领取弹框
         */
        async cancelPresentMoneyTool() {
            let _this = this
            let userinfo = await storage.getItem('userinfo')
            if(userinfo){
                this.presentMoneyTool = false
                // this.currenCountArray.forEach(function(item,index){
                //     if(item.state==1){
                //         item['state'] = 0
                //         _this.$set(_this.currenCountArray,index,item)
                //         _this.submitDataArray.unshift(item)
                //     }
                    
                // })
                // storage.setItem('currenCountArrayKey',this.currenCountArray)
                // let choosePresentMoney = this.currenCountArray.filter(function(item,index){
                //     if(item.state==0){
                //         return item
                //     }
                // })
                //this.allPresentMoney(choosePresentMoney)
                if(this.submitDataArray.length){
                    this.getRechargeByReading()
                }
                
            }else{
                this.presentMoneyTool = false
            }
        },
        /**
         * 点击领取
         */
        async clickPresentMoney(item,index) {
            if(item.state==1){
                let userinfo = await storage.getItem('userinfo')
                if(userinfo){
                    var setupObj = this.currenCountArray[index]
                    setupObj['state'] = 0 // 状态修改为已领取
                    this.$set(this.currenCountArray,index,setupObj)
                    this.submitDataArray.unshift(item)
                    storage.setItem('currenCountArrayKey',this.currenCountArray)
                    let choosePresentMoney = this.currenCountArray.filter(function(item,index){
                        if(item.state==0){
                            return item
                        }
                    })
                    this.allPresentMoney(choosePresentMoney)
                }else{
                    this.readLoginBackTool = true
                }    
            }  
        },
        /**
         * 保存总的赠金信息
         */
        async allPresentMoney(choosePresentMoney) {
            let todyTimeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000 // 当天0点0分0秒时间戳
            let allPresentMoney = await storage.getItem('allPresentMoneyKey') || {}
            if(choosePresentMoney.length){
                let pocket = choosePresentMoney.map(function(item,index){
                    let obj = {
                        duration: item.duration,
                        generate_time: item.generate_time
                    }
                    return obj
                })
                this.$set(allPresentMoney,todyTimeStamp,pocket)
                
                // 删除一个月之前
                var arr = Object.keys(allPresentMoney)
                if(arr.length>30){
                    arr.forEach(function(key,index){
                        if(index>29){
                            delete allPresentMoney[key]
                        }
                    })
                }
                await storage.setItem('allPresentMoneyKey',allPresentMoney)
                await storage.setItem('choosePresentMoneyKey',pocket)
            }
        },
        /**
         * 获取验证
         */
        async getRechargeByReading() {
            let userinfo = await storage.getItem('userinfo')
            if(userinfo){
                let todyTimeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000 // 当天0点0分0秒时间戳
                let key = 'signKey'+todyTimeStamp+userinfo.uid
                let sign = await storage.getItem(key)
                if(sign){
                    this.submitData(userinfo,sign)
                }else{
                    let res = await axios.get(api.beginReading)
                    if(res){
                        let sign = res.data.data.sign
                        this.submitData(userinfo,sign)
                        let yesterdayTimeStamp = todyTimeStamp-86400 // 昨天0点0分0秒时间戳
                        let yesterdaykey = 'signKey'+yesterdayTimeStamp+userinfo.uid
                        storage.removeItem(yesterdaykey)
                        await storage.setItem(key,sign)
                    }
                }
            }
        },
        /**
         * 上传数据
         */
        async submitData(userinfo,sign) {
            let pocket = this.submitDataArray.map(function(item,index){
                let obj = {
                    duration: item.duration,
                    generate_time: item.generate_time
                }
                return obj
            })
            let paramsData = {
                uid: userinfo.uid,
                token: userinfo.token,
                sign: sign,
                pocket: pocket
            }
            let result = await axios.post(api.rechargeByReading,qs.stringify(paramsData))
            if(result){
                Toast("领取成功，请在'我的-我的现金'页面查看您的现金额度")
                this.submitDataArray = []
            }
            
        },
        contnetFilter(value) {
            if(value){
                let str = value.replace(/\n|\r\n/g,"!+")
                let arr = str.split('!+')
                let str1 = ''
                arr.forEach((val,index)=>{

                    if(val!=' '){
                        str1 += `<p>${val}<p/>`
                    }
                }) 
                return str1
            }
        },
        downloadAction() {
            window.location.href='https://kuaiyanapps.oss-cn-shenzhen.aliyuncs.com/download/index.html'
        }
    },
    components: {
        LoginReg
    },
    beforeDestroy(){
        clearInterval(this.intervalid); // 关闭定时器
    },
    async asyncData({query}){
        if(process.server){
            let [storeInfo, readData] = await axios.all([
              axios.get(api.unLogin,{params:{novelId:query.novelId}}),
              axios.get(api.read,{params:query})
            ])
            return {
                storeInfo:storeInfo.data.data[0],
                readData: readData.data.data
            }
        }
    },
    async beforeRouteLeave(to, from, next) {
        let toPath = to.path
        if(toPath=='/read/source' || toPath=='/read/catalog'){
            next()
            return
        }
        let {query} = from
        let novelId = parseInt(query.novelId)
        let arr = await storage.getItem('bookshelfIdKey') || []
        if(arr.indexOf(novelId) > -1){
            next()
            return
        }
        let _this = this 
        arr.unshift(novelId)
        MessageBox.confirm(`是否将正在阅读的书籍《${this.storeInfo.name}》加入书架?`).then(action => {
            _this.syncShelfAction(arr)
            setTimeout(function(){
                next()
            },300)
        }).catch(cancel => {
            setTimeout(function(){
                next()
            },300)
        }); 
        
    }
  }
</script>

